export default class Query {
    //基础配置项
    static options = {
        host: '',
        type: 'json',
    }
    /**
     * @param string url  请求地址
     * @param object data POST/PUT等提交到后台的数据
     */
    constructor(type = 'get', url, data, options = {}) {
        this.type = type
        this.url = Query.options.host + url
        this.data = this.format(data)
        this.options = Object.assign(Query.options, options)
        this.xhr = new XMLHttpRequest()
    }
    //全局基础配置
    static config(options) {
        Query.options = options
    }
    //生成POST请求数据
    format(data) {
        let form = new FormData()
        for (const [key, value] of Object.entries(data)) {
            form.append(key, value)
        }
        return form
    }
    //发送GET请求
    static get(url, options = {}) {
        return new Query('get', url, {}, options).ajax()
    }
    //发送POST请求
    static post(url, data, options = {}) {
        return new Query('post', url, data, options).ajax()
    }
    //AJAX异步请求发送
    ajax() {
        return new Promise((resolve, reject) => {
            this.xhr.open(this.type, this.url)
            this.xhr.responseType = this.options.type
            this.xhr.send(this.data)
            this.xhr.onload = () => {
                if (this.xhr.status === 200) {
                    resolve(this.xhr.response)
                } else {
                    reject(this.xhr.responseText)
                }
            }
        })
    }
}
